package com.inspur.cloud.service.ambari;

import com.inspur.cloud.dao.ambari.ComponentDesiredStateDao;
import com.inspur.cloud.dao.ambari.HostsDao;
import com.inspur.cloud.entity.ambari.ComponentDesiredStateEntity;
import com.inspur.cloud.entity.ambari.HostsEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ComponentDesiredStateService {
    @Autowired
    private ComponentDesiredStateDao componentDesiredStateDao;
    @Autowired
    private HostsDao hostsDao;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public ComponentDesiredStateEntity findByComponentName(String componentName) {
        List<ComponentDesiredStateEntity> list=componentDesiredStateDao.findByComponentName(componentName);
        if(list!=null && list.size()==1){
            return list.get(0);
        }else if(list!=null && list.size()>1){
            ComponentDesiredStateEntity entity;
            for (ComponentDesiredStateEntity component : list) {
                logger.info("component host:{}",component.getHostId());
            }
            return list.get(0);
        }

        return null;
    }

    public HostsEntity findMaster(String componentName){
        List<ComponentDesiredStateEntity> list=componentDesiredStateDao.findByComponentName(componentName);
        if(list==null||list.size()==0) return null;
        if(list.size()==1){
            return hostsDao.findByhostId(list.get(0).getHostId());
        }
        for (ComponentDesiredStateEntity componentDesiredStateEntity : list) {
            Integer hostId=componentDesiredStateEntity.getHostId();
            HostsEntity host=hostsDao.findByhostId(hostId);
            if(host.getHostName().indexOf("master")>-1){
                return host;
            }

        }
        return hostsDao.findByhostId(list.get(0).getHostId());
    }


    /**
     * 判断集群中是否存在某个组件
     * @param componentName 组件名
     * @return boolean
     */
    public boolean isComponentExist(String componentName) {
        List<ComponentDesiredStateEntity> list = componentDesiredStateDao.findByComponentName(componentName);
        return list.size() > 0;
    }

}
